const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const os = require('os');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const sqlite3 = require('sqlite3').verbose();

// 定义 JWT 密钥
const JWT_SECRET = 'your_jwt_secret_key';

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// 获取 IP 地址函数
function getIPAddress() {
  const interfaces = os.networkInterfaces();
  let ipAddress = '127.0.0.1';
  for (const iface of Object.values(interfaces)) {
    for (const details of iface) {
      if (details.family === 'IPv4' && !details.internal) {
        ipAddress = details.address;
        break;
      }
    }
  }
  return ipAddress;
}

// 初始化 SQLite 数据库
const db = new sqlite3.Database(path.join(__dirname, 'users.db'), (err) => {
  if (err) {
    console.error('数据库连接失败:', err.message);
  } else {
    console.log('成功连接到 SQLite 数据库');
    // 创建用户表
    db.run(`CREATE TABLE IF NOT EXISTS users (
      username TEXT PRIMARY KEY,
      password TEXT NOT NULL,
      avatar TEXT,
      gender TEXT,
      nick_name TEXT,
      motto TEXT
    )`);
  }
});

// 登录接口
app.post('/login', (req, res) => {
  const { username, password, gender = '', nick_name = '', motto = '' } = req.body;

  // 检查用户是否存在
  db.get('SELECT * FROM users WHERE username = ?', [username], (err, user) => {
    if (err) {
      return res.status(500).json({ code: 10005, data: { error: '数据库错误' } });
    }

    if (!user) {
      // 用户不存在，创建新用户
      db.run(
        'INSERT INTO users (username, password, avatar, gender, nick_name, motto) VALUES (?, ?, ?, ?, ?, ?)',
        [username, password, '', gender, nick_name, motto],
        function(err) {
          if (err) {
            return res.status(500).json({ code: 10005, data: { error: '数据库错误' } });
          }
          
          // 使用 JWT 生成 token
          const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '1h' });
          res.json({ code: 10000, data: { token } });
        }
      );
    } else {
      // 用户已存在，验证密码
      if (user.password !== password) {
        return res.status(401).json({ code: 10001, data: { error: '密码错误' } });
      }
      
      // 使用 JWT 生成 token
      const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '1h' });
      res.json({ code: 10000, data: { token } });
    }
  });
});

// 配置上传目录
const uploadDir = path.join(__dirname, 'public', 'upload');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const randomName = `${Date.now()}-${Math.random().toString(36).substring(2)}${ext}`;
    cb(null, randomName);
  }
});

const fileFilter = (req, file, cb) => {
  const filetypes = /jpeg|jpg|png|gif/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if (extname && mimetype) {
    return cb(null, true);
  } else {
    cb(new Error('仅允许上传图片文件！'));
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制文件大小为 5MB
  },
  fileFilter: fileFilter
});

// 上传头像接口，合并处理逻辑并使用正确的错误处理中间件顺序
app.post('/upload-avatar', upload.single('avatar'), (req, res, next) => {
    if (!req.file) {
        return res.status(400).json({ code: 10002, data: { error: '未选择文件' } });
    }

    const token = req.headers['authorization']?.split(' ')[1];
    if (!token) {
        return res.status(401).json({ code: 10003, data: { error: '未提供 token' } });
    }

    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        const username = decoded.username;
        const ipAddress = getIPAddress();
        const avatarUrl = `http://${ipAddress}:3000/upload/${req.file.filename}`;

        db.run('UPDATE users SET avatar = ? WHERE username = ?', [avatarUrl, username], function(err) {
            if (err) {
                return res.status(500).json({ code: 10005, data: { error: '数据库错误' } });
            }
            res.json({ code: 10000, data: { avatarUrl } });
        });
    } catch (error) {
        return res.status(401).json({ code: 10003, data: { error: '无效的 token' } });
    }
});

// 错误处理中间件，放在路由之后
app.use('/upload-avatar', (err, req, res, next) => {
    if (err) {
        return res.status(400).json({ code: 10002, data: { error: err.message } });
    }
    next();
});

// 用户信息接口
app.get('/user-info', (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) {
    return res.status(401).json({ code: 10003, data: { error: '未提供 token' } });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    const username = decoded.username;
    
    db.get('SELECT * FROM users WHERE username = ?', [username], (err, user) => {
      if (err) {
        return res.status(500).json({ code: 10005, data: { error: '数据库错误' } });
      }
      
      if (!user) {
        return res.status(404).json({ code: 10004, data: { error: '用户不存在' } });
      }
      
      res.json({ code: 10000, data: {
        username,
        avatar: user.avatar,
        gender: user.gender,
        nick_name: user.nick_name,
        motto: user.motto
      }});
    });
  } catch (error) {
    return res.status(401).json({ code: 10003, data: { error: '无效的 token' } });
  }
});

// 修改用户信息接口
app.post('/update-user-info', (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) {
    return res.status(401).json({ code: 10003, data: { error: '未提供 token' } });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    const username = decoded.username;
    const { gender, nick_name, motto } = req.body;
    
    const sql = 'UPDATE users SET gender = ?, nick_name = ?, motto = ? WHERE username = ?';
    db.run(sql, [gender, nick_name, motto, username], function(err) {
      if (err) {
        return res.status(500).json({ code: 10005, data: { error: '数据库错误' } });
      }
      res.json({ code: 10000, data: { message: '用户信息更新成功' } });
    });
  } catch (error) {
    return res.status(401).json({ code: 10003, data: { error: '无效的 token' } });
  }
});

// 添加测试路由
app.get('/test', (req, res) => {
  const { code = 10000, message = '测试成功' } = req.query;
  res.json({
    code: parseInt(code),
    data: {
      message: message
    }
  });
});

// 创建 public 目录
const publicDir = path.join(__dirname, 'public');
if (!fs.existsSync(publicDir)) {
  fs.mkdirSync(publicDir);
}

const PORT = 3000;
app.listen(PORT, () => {
  const ipAddress = getIPAddress();
  console.log(`Server is running on port ${PORT}`);
  console.log(`Access link with IP: http://${ipAddress}:${PORT}`);
});

// 清空用户信息和上传图片的接口
app.get('/clear-all', (req, res) => {
  // 清空用户表
  db.run('DELETE FROM users', (err) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ code: 10005, message: '数据库操作失败' });
    }
    
    // 清空上传的图片
    const fs = require('fs');
    const path = require('path');
    const uploadDir = path.join(__dirname, 'public/upload');
    
    fs.readdir(uploadDir, (err, files) => {
      if (err) {
        console.error(err);
        return res.status(500).json({ code: 10005, message: '清空图片失败' });
      }
      
      for (const file of files) {
        fs.unlink(path.join(uploadDir, file), (err) => {
          if (err) {
            console.error(err);
          }
        });
      }
      
      res.json({ code: 200, message: '用户信息和上传图片已清空' });
    });
  });
});